package cn.itcast.service.cargo.impl;

import cn.itcast.dao.cargo.ContractDao;
import cn.itcast.dao.cargo.ExportDao;
import cn.itcast.dao.cargo.PackingListDao;
import cn.itcast.dao.cargo.ShippingOrderDao;
import cn.itcast.domain.ResultInfo;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ShippingOrderService;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ShippingOrderServiceImpl implements ShippingOrderService {
    @Autowired
    private PackingListDao packingListDao;

    @Autowired
    private ShippingOrderDao shippingOrderDao;

    @Autowired
    private ExportDao exportDao;

    @Autowired
    private ContractDao contractDao;

    @Override
    public void save(ShippingOrder shippingOrder) {
        PackingList packingList = packingListDao.selectById(shippingOrder.getShippingOrderId());
        shippingOrder.setLoadingDate(packingList.getPackingDate());
        shippingOrder.setState(0);
        shippingOrder.setCreateTime(new Date());
        shippingOrderDao.insert(shippingOrder);

        packingList.setState(1);
        packingListDao.updateById(packingList);

        String exportIds = packingList.getExportIds();
        String[] split = exportIds.split(",");
        if (split.length != 0){
            exportDao.updateStateByIds(split,4);
        }

    }

    @Override
    public PageInfo<ShippingOrder> findByPage(Integer pageNum, Integer pageSize, String loginUserCompanyId) {
        PageHelper.startPage(pageNum,pageSize);

        List<ShippingOrder> packingLists = shippingOrderDao.selectList(new QueryWrapper<ShippingOrder>().eq("company_id", loginUserCompanyId));

        PageInfo<ShippingOrder> pageInfo = new PageInfo<>(packingLists);
        return pageInfo;
    }

    @Override
    public ResultInfo delete(String shippingOrderId) {
        int count = shippingOrderDao.delete(new QueryWrapper<ShippingOrder>().eq("shipping_order_id", shippingOrderId).ne("state", 1));
        if (count==1){
            PackingList packingList = packingListDao.selectById(shippingOrderId);
            packingList.setState(0);
            packingListDao.updateById(packingList);

            String exportIds = packingList.getExportIds();
            String[] split = exportIds.split(",");
            if (split.length != 0){
                exportDao.updateStateByIds(split,3);
            }

            return new ResultInfo(true);
        }else {
            return new ResultInfo(false,"删除失败，请检查装箱单状态！");
        }
    }

    @Override
    public ResultInfo invoice(String shippingOrderId) {
        //查询shippingOrder
        ShippingOrder shippingOrder = shippingOrderDao.selectById(shippingOrderId);
        //检验委托单
        if (shippingOrder==null)
            return new ResultInfo(false,"委托单不存在!");
        if (shippingOrder.getState()!=0)
            return new ResultInfo(false,"该委托单已生成发票");

        //创建发票并填充数据
        Invoice invoice = new Invoice();
        //发票编号INVOICE_ID一个发票对应一个委托单
        invoice.setInvoiceId(shippingOrderId);
        //SC_NO报运的合同号
        PackingList packingList = packingListDao.selectById(shippingOrderId);
        invoice.setScNo(packingList.getExportNos());
        //发票金额invoice_money报运金额 + 装箱金额 + 委托金额
        BigDecimal totalPrice = new BigDecimal(0);
        //从packingList中获取装箱费用packingMoney
        totalPrice = packingList.getPackingMoney().add(totalPrice);

        //通过packingList，查询所有export
        String exportIds = packingList.getExportIds();
        List<String> exportIdList = Arrays.stream(exportIds.split(",")).collect(Collectors.toList());
        ExportExample exportExample = new ExportExample();
        exportExample.createCriteria().andIdIn(exportIdList);
        List<Export> exports = exportDao.selectByExample(exportExample);

        //通过所有的export查询所有的购销合同contractId
        List<String> contractIdList = new LinkedList<>();
        for (Export export : exports) {
            String contractIds = export.getContractIds();
            Arrays.stream(contractIds.split(",")).forEach(s -> contractIdList.add(s));
        }

        //通过contractIdList获取所有购销合同contract
        ContractExample contractExample = new ContractExample();
        contractExample.createCriteria().andIdIn(contractIdList);
        List<Contract> contractList = contractDao.selectByExample(contractExample);

        StringBuilder tradeTerms = new StringBuilder();
        //遍历contract
        for (Contract contract : contractList) {
            //从已查出的contract中获取总报运金额
            totalPrice = totalPrice.add(BigDecimal.valueOf(contract.getTotalAmount()));

            //贸易条款TRADE_TERMS从购销合同查询获取，逗号隔开
            if (contract.getTradeTerms()!=null){
                tradeTerms.append(contract.getTradeTerms()).append(",");
            }

        }
        //将所有的contract的tradeTerms整合成字符串，保存进invoice
        if (tradeTerms.length()!=0){
            invoice.setTradeTerms(tradeTerms.substring(0,tradeTerms.length()-1));
        }else {
            invoice.setTradeTerms("");
        }

        //将总价格保存进invoice
        invoice.setInvoiceMoney(totalPrice);

        //TODO 委托金额不存在

        //返回结果集
        return new ResultInfo(true,"",invoice);
    }

    @Override
    public ShippingOrder findById(String id) {
        return shippingOrderDao.selectById(id);
    }
}
